package com.ruoyi.store.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.mchange.lang.LongUtils;
import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.agent.service.ISysAgentService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.order.Utils.OrderUtils;
import com.ruoyi.packages.mapper.SysStorePackageMapper;
import com.ruoyi.store.domain.SysStorePackage;
import com.ruoyi.store.domain.SysStoreStatusDTO;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.domain.SysRoleMenu;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.store.mapper.SysStoreMapper;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.service.ISysStoreService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;

import static com.ruoyi.common.utils.SecurityUtils.encryptPassword;
import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-12
 */
@Service
public class SysStoreServiceImpl implements ISysStoreService
{
    @Autowired
    private SysStoreMapper sysStoreMapper;

    @Autowired
    private SysAgentMapper sysAgentMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleDeptMapper roleDeptMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysUserMapper userMapper;







    @Autowired
    private SysUserPostMapper userPostMapper;


    @Autowired
    private ISysDeptService deptService;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysUserService userService;
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);


    @Autowired
    private ISysAgentService agentService;

    @Autowired
    private SysAgentMapper agentMapper;

    @Autowired
    private SysStorePackageMapper storePackageMapper;
    /**
     * 查询管理
     *
     * @param id 管理主键
     * @return 管理
     */
    @Override
    public SysStore selectSysStoreById(Long id)
    {
        SysStore sysStore = sysStoreMapper.selectSysStoreById(id);
        Long storeId = sysStore.getId();

        //根据商铺id查询对应的套餐

       List<Long> packagesIds= sysStoreMapper.selectPackageIdsByStoreId(storeId);
        sysStore.setPackageIds(packagesIds.toArray(new Long[packagesIds.size()]));
        return sysStore;
    }

    /**
     * 查询管理列表
     *
     * @param sysStore 管理
     * @return 管理
     */
    @Override
//    @DataScope(userAlias = "u",deptAlias = "d")
    public List<SysStore> selectSysStoreList(SysStore sysStore)
    {
        Long deptId = SecurityUtils.getDeptId();
        //根据当前部门id查询对应的代理商id

        if (deptId!=100) {
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (!CollectionUtils.isEmpty(agents)) {
                Long agentId = agents.get(0).getId();
                sysStore.setAgentId(agentId);
                return sysStoreMapper.selectSysStoreList(sysStore);
            }
            else {
                throw new ServiceException("您没有权限查看");
            }
        }
        sysStore.setAgentId(0l);

        return sysStoreMapper.selectSysStoreList(sysStore);
    }

    /**
     * 新增管理
     *
     * @param sysStore 管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSysStore(SysStore sysStore)
    {

        //商户手机号校验，邮箱校验

        if (!OrderUtils.isValidMobileNumber(sysStore.getPhone())) {
            throw new ServiceException("手机号格式有误");
        }

        if (!OrderUtils.isValidEmail(sysStore.getEmail())) {
            throw new ServiceException("邮箱格式有误");
        }


        //手机号唯一校验
        SysUser sysUser = new SysUser();
        sysUser.setPhonenumber(sysStore.getPhone());

        List<SysUser> users = userService.selectUserList(sysUser);
        if (!CollectionUtils.isEmpty(users)) {
            throw new ServiceException("手机号已存在");
        }
        //商户标识唯一校验,只查询同一代理商下的商户对应的标识是否有相同得
        Long agentId=0l;
        if (!SecurityUtils.getDeptId().equals(100l)) {
            List<SysAgent> agents1 = agentMapper.selectSysAgentByDeptId(SecurityUtils.getDeptId());
            if (CollectionUtils.isEmpty(agents1)) {
                //说明当前操作人代理商信息不存在
                throw new ServiceException("当前代理商信息异常");
            }

            agentId = agents1.get(0).getId();

        }

        SysStore sysStore1 = new SysStore();
        sysStore1.setAgentId(agentId);
        sysStore1.setMark(sysStore.getMark());
        List<SysStore> sysStores = sysStoreMapper.selectSysStoreList(sysStore1);
        if (!CollectionUtils.isEmpty(sysStores)) {
            throw new ServiceException("商户标识已存在");
        }


        sysStore.setCreateTime(DateUtils.getNowDate());
        sysStore.setStatus("0");
        //封装对应的商铺信息
        Long userId = SecurityUtils.getUserId();
        Long deptId = SecurityUtils.getDeptId();


//        sysStore.setUserId(userId);
//        sysStore.setDeptId(deptId);
        List<SysAgent> agents= agentMapper.selectSysAgentByDeptId(deptId);
        //根据当前部门id查询对应的代理商id
        if (deptId==100) {
            //如果dept_Id=100 表示是管理员
            sysStore.setAgentId(0l);
            sysStore.setAgentName("————");
        } else {
          //根据当前用户的部门id查询对应的代理商表

           if (CollectionUtils.isEmpty(agents)) {
               throw new ServiceException("对应代理商不存在且当前用户非管理员");
           }

           //通过id查询对应的代理的商铺数量
          Long storeNum=  agentMapper.selectSysAgentStoreNumById(agents.get(0).getId());
            SysAgent sysAgent = agents.get(0);
            Long id = sysAgent.getId();
            String name = sysAgent.getName();
            sysStore.setAgentId(id);
            sysStore.setAgentName(name);

            //更新对应的代理商商铺数量
//            Long storeNum = sysAgent.getStoreNum();
            if (storeNum==null) {
                storeNum=0l;
            }

            ++storeNum;
            Long num = storeNum;


            agentMapper.addStoreNumById(num,sysAgent.getId());
        }






        //新增对应的角色
        // 新增角色信息

        //todo 对商铺的标识进行校验

        SysRole role = new SysRole();
        role.setRoleName(sysStore.getName()+"_商铺管理员");
        role.setRoleKey(sysStore.getMark());
        role.setRoleSort(0);
        role.setStatus("0");
//        role.setIsHide(1);

        role.setDeptCheckStrictly(true);
        role.setMenuCheckStrictly(true);
        Long[] menuids = {1l,100l,101l,103l,1000l,1001l,1002l,1003l,1004l,1005l,1006l,1007l,1008l,1009l,1010l,1011l,1016l,1017l,1018l,1019l,2071l,2090l,2164l,2165l,2166l,2167l,2168l,2169l,2146l,2147l,2148l,2149l,2150l,2151l,2158l,2159l,2160l,2161l,2162l,2163l,2176l,2177l,2178l,2179l,2180l,2181l,2182l,2183l,2184l,2185l,2186l,2187l,2188l,2189l,2190l,2191l};
        role.setMenuIds(menuids);
        role.setUserId(SecurityUtils.getUserId());
        role.setDeptId(SecurityUtils.getDeptId());

        roleMapper.insertRole(role);

        insertRoleMenu(role);

        //新增对应的部门
        SysDept dept = new SysDept();
        dept.setDeptName(sysStore.getName());
        dept.setEmail(sysStore.getEmail());
        dept.setLeader(sysStore.getUserName());
        dept.setOrderNum(0);
        //设置对应的父类节点id为当前代理商部门
        dept.setParentId(deptId);
        dept.setPhone(sysStore.getPhone());
        dept.setStatus("0");
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        deptMapper.insertDept(dept);
        //修改角色的数据权限信息
        role.setDataScope("3");
        roleService.checkRoleAllowed(role);
//        roleService.checkRoleDataScope(role.getRoleId());
        ArrayList<Long> longs = new ArrayList<>();

        Long[] arr = new Long[longs.size()];

        longs.add(dept.getDeptId());
        Long[] longs1 = longs.toArray(arr);
        role.setDeptIds(longs1);
        roleService.authDataScope(role);

        // 修改角色信息
        roleMapper.updateRole(role);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
        // 新增角色和部门信息（数据权限）
        insertRoleDept(role);


        //添加对应用户

        SysUser user = new SysUser();
        user.setDeptId(dept.getDeptId());
        user.setEmail(sysStore.getEmail());
        user.setNickName(sysStore.getUserName());
        user.setPassword(SecurityUtils.encryptPassword(sysStore.getPassword()));
        user.setPhonenumber(sysStore.getPhone());
        //密码加密

//        deptService.checkDeptDataScope(user.getDeptId());
//        roleService.checkRoleDataScope(user.getRoleIds());

        user.setCreateBy(getUsername());
//        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        Long[] postIds = new Long[1];
        postIds[0]=4l;
        user.setPostIds(postIds);
        user.setRemark("");
//        user.setRoleId(role.getRoleId());
        Long[] longs2 = new Long[1];
        longs2[0]=role.getRoleId();
        user.setRoleIds(longs2);
        user.setSex("0");
        user.setStatus("0");
        user.setUserName(sysStore.getUserName());
        // 新增用户信息

        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
//
//        sysStore.setUserId(SecurityUtils.getUserId());
//        sysStore.setDeptId(SecurityUtils.getDeptId());
        user.setUserId(user.getUserId());
        user.setDeptId(dept.getDeptId());
        //更新对应代理商的商铺数量
//
//        Long storeNum = agents.get(0).getStoreNum();
//        if (storeNum==null || storeNum.equals(null)) {
//            storeNum=0l;
//        }
//        ++storeNum;
//
//        agentMapper.updateSysAgentStoreNum(storeNum,agents.get(0).getId());






        sysStore.setUserId(user.getUserId());
        sysStore.setDeptId(dept.getDeptId());
        sysStore.setPassword(encryptPassword(sysStore.getPassword()));
        int i = sysStoreMapper.insertSysStore(sysStore);

        //获取到对应的套餐id集合，插入到映射表中
        Long[] packageIds = sysStore.getPackageIds();
        List<Long> packageIdss = Arrays.stream(packageIds).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(packageIdss) &&packageIdss.size()>0 ) {
            Long storeId = sysStore.getId();
            List<SysStorePackage> storePackages = new ArrayList<>();
            for (Long idss : packageIdss) {

                SysStorePackage sysStorePackage = new SysStorePackage();
                sysStorePackage.setStoreId(storeId);
                sysStorePackage.setPackageId(idss);
                storePackages.add(sysStorePackage);
            }
            sysStoreMapper.insertSysStorePackage(storePackages);
        }


        SysRole sysRole = new SysRole();
        sysRole.setRoleId(role.getRoleId());
        sysRole.setUserId(user.getUserId());
        sysRole.setDeptId(dept.getDeptId());
        roleMapper.updateRole(sysRole);
        return i;
    }
    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    public int insertRoleMenu(SysRole role)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds())
        {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(SysRole role)
    {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds())
        {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0)
        {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }
    /**
     * 修改管理
     *
     * @param sysStore 管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSysStore(SysStore sysStore)
    {
        sysStore.setUpdateTime(DateUtils.getNowDate());
        Long[] packageIds = sysStore.getPackageIds();
        List<Long> packageIdss = Arrays.asList(packageIds);

        Long storeId = sysStore.getId();
        //删除对应商铺和套餐的所有对应关系
        storePackageMapper.deleteAllByStoreId(storeId);

        //插入套餐和商铺的关系

        if (CollectionUtils.isEmpty(packageIdss) || packageIdss.size()<=0) {
            return 1;
        }
        List<SysStorePackage> storePackages = new ArrayList<>();

        for (Long idss : packageIdss) {
            SysStorePackage sysStorePackage = new SysStorePackage();
            sysStorePackage.setStoreId(storeId);
            sysStorePackage.setPackageId(idss);
            storePackages.add(sysStorePackage);
        }

        if (sysStore.getPassword()!=null && sysStore.getPassword()!="") {
            //获取到密码修改对应的商户管理员账号
            SysStore sysStore1 = sysStoreMapper.selectSysStoreById(sysStore.getId());
            if (sysStore1==null) {
                throw new ServiceException("商户不存在");
            }
            Long userId = sysStore1.getUserId();
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser.setPassword(SecurityUtils.encryptPassword(sysStore.getPassword()));
            userMapper.updateUser(sysUser);
        }

        sysStoreMapper.insertSysStorePackage(storePackages);



        return sysStoreMapper.updateSysStore(sysStore);
    }

    /**
     * 批量删除管理
     *
     * @param ids 需要删除的管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteSysStoreByIds(Long[] ids)
    {
        //获取到ids的个数
        Long length = Long.valueOf(ids.length);

        //校验是否所有的id都存在
        List<Long> collect = Arrays.stream(ids).collect(Collectors.toList());
       List<SysStore> sysStores = sysStoreMapper.listByIds(collect);

       Long numslong = Long.valueOf(sysStores.size());
       if (numslong!=length) {
           throw new ServiceException("商铺数据异常");
       }
        //修改对应的代理商表
        Long deptId = SecurityUtils.getDeptId();

       //根据当前部门查询对应的代理
        if (deptId!=100) {
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商数据异常");
            }
            Long aLong = agentMapper.selectSysAgentStoreNumById(agents.get(0).getId());

            if (aLong< length) {
                throw new ServiceException("代理商数据异常");
            }

            Long newNum = aLong-length;
            agentMapper.updateSysAgentStoreNum(newNum,agents.get(0).getId());


        }



        return sysStoreMapper.deleteSysStoreByIds(ids);
    }

    /**
     * 删除管理信息
     *
     * @param id 管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteSysStoreById(Long id)
    {

        //查询对应的id的商铺是否存在

        SysStore sysStore = sysStoreMapper.selectSysStoreById(id);
        if (sysStore==null) {
            throw new ServiceException("店铺不存在");
        }

        //修改对应的代理商
        //根据当前部门查询对应的代理
        Long deptId = SecurityUtils.getDeptId();
        if (deptId!=100) {
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商数据异常");
            }
            Long aLong = agentMapper.selectSysAgentStoreNumById(agents.get(0).getId());



            Long newNum = aLong-1;
            agentMapper.updateSysAgentStoreNum(newNum,agents.get(0).getId());
        }


        //将该名下所有的管理员账号禁用
        //判断当前用户是否有权限操作


        //判断当前商户商是否存在
        SysStore sysStore1 = sysStoreMapper.selectSysStoreById(id);
        if (sysStore1==null) {
            throw new ServiceException("商户不存在");
        }

        if (deptId.equals(100l)) {
            SysStore sysStore01 = sysStoreMapper.selectSysStoreById(id);
            if (!sysStore01.getAgentId().equals(0l)) {
                //不能操作
                throw new ServiceException("您没有权限操作");
            }
        }
        else {
            //根据当前部门id获取到代理商id
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商信息异常");
            }
            SysAgent sysAgent = agents.get(0);
            if (!sysStore1.getAgentId().equals(sysAgent.getId())) {
                throw new ServiceException("您没有权限操作");
            }
        }

            userMapper.updateStatusByDeptId(sysStore1.getDeptId(),"1");









        return sysStoreMapper.deleteSysStoreById(id);
    }

    @Override
    public void UpOrNoAgentStatus(SysStoreStatusDTO statusDTO) {
        //判断当前用户是否有权限操作

        Long deptId = SecurityUtils.getDeptId();
        //判断当前代理商是否存在
        SysStore sysStore1 = sysStoreMapper.selectSysStoreById(statusDTO.getStoreId());
        if (sysStore1==null) {
            throw new ServiceException("代理商不存在");
        }

        if (deptId.equals(100l)) {
            SysStore sysStore = sysStoreMapper.selectSysStoreById(statusDTO.getStoreId());
            if (!sysStore.getAgentId().equals(0l) && !deptId.equals(100l)) {
                //不能操作
                throw new ServiceException("您没有权限操作");
            }
        }
        else {
            //根据当前部门id获取到代理商id
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商信息异常");
            }
            SysAgent sysAgent = agents.get(0);
            if (!sysStore1.getAgentId().equals(sysAgent.getId())) {
                throw new ServiceException("您没有权限操作");
            }
        }


       int i = sysStoreMapper.updateSysStoreStatus(statusDTO.getStoreId(),statusDTO.getStatus());


        if (i<=0) {
            throw new ServiceException("修改失败");
        }

        //修改对应的代理商下的用户账号：
        if (statusDTO.getStatus().equals("1")) {
            //禁用所有的该代理商用户
            userMapper.updateStatusByDeptId(sysStore1.getDeptId(),statusDTO.getStatus());



        }
        else if (statusDTO.getStatus().equals("0")) {
            //仅启动当前代理商管理员
            userMapper.updateStatusByUserId(sysStore1.getUserId(),statusDTO.getStatus());
        }





    }
}
